#coding: utf8

import sys
sys.path.append("./")

import json
from flask import Flask, request, current_app, g
from flask_cors import *
from src.login import auth_required, web_login_common, login_out, get_auth_code
from src.config import Web as C
from src.libs.log import L
from src.common.response import NormalResponseJson, ErrorResponseJson, ErrorResponseData
import src.project as P
import src.module as M
import src.task as T
import src.record as RC
import src.report as RP
import src.change_task as CT

app = Flask(__name__)
CORS(app, supports_credentials=True)
app.config['SECRET_KEY'] = 'AreUOK'
app.config['TOKEN_EXPIRATION'] = 720000


@app.route('/')
def index():
    return "Welcome..."

'''验证码'''
@app.route('/securityCode')
def get_code():
    return get_auth_code(app)   

@app.route('/login', methods=['GET', 'POST'])    
def webLogin():
    '''Form field: username, password, securityCode, tms'''
    '''第二个参数传1则无需验证码'''
    return web_login_common(request, 1)

@app.route('/isLogin', methods=['GET', 'POST'])
@auth_required('lv0')
def is_login(user):
    L.info("User %s Request login status" % user)
    return NormalResponseJson({})

@app.route('/loginOut', methods=['GET', 'POST'])
@auth_required('lv0')    
def _login_out(user, R):
    return login_out(user)

'''----------------------------------正式业务开始---------------------------------------'''
@app.route('/createProject', methods=['GET', 'POST'])
@auth_required('lv0')    
def _create_project(user, R):
    name = R.get('name', '')
    description = R.get('description', '')
    if name == '' or description == '': return ErrorResponseJson('项目名和描述不能为空！') 
    data = P.create_project(user, name, description) 
    
    if not data: return ErrorResponseJson('操作失败！')
    
    return NormalResponseJson({'id': data}) 

@app.route('/listProject', methods=['GET', 'POST'])
@auth_required('lv0')    
def _list_project(user, R):
    create_user = R.get('createUser', '')
    category = R.get('category', '')
    department = R.get('department', '')
    page = int(R.get('page', 0))
    size = int(R.get('page', 26))
    data = P.get_project_list(create_user, category, department, page, size)
    
    return NormalResponseJson(data)


@app.route('/createModule', methods=['GET', 'POST'])
@auth_required('lv0')    
def _create_module(user, R):
    pid = R.get('pid', '')
    name = R.get('name', '')
    description = R.get('description', '')
    if pid == "" or name == '' or description == '': return ErrorResponseJson('模块名和描述不能为空！') 
    data, msg = M.create_module(pid, user, name, description)
    
    if not data: return ErrorResponseJson(msg if msg else '操作失败，请检查是否填写完整！')
    
    return NormalResponseJson({'id': data}) 

@app.route('/listModule', methods=['GET', 'POST'])
@auth_required('lv0')    
def _list_module(user, R):
    pid = R.get('pid', '')
    create_user = R.get('createUser', '')
    category = R.get('category', '')
    department = R.get('department', '')
    
    data = M.get_module_list(pid, create_user, category, department)
    
    return NormalResponseJson(data)


@app.route('/createTask', methods=['GET', 'POST'])
@auth_required('lv0')    
def _create_task(user, R):
    pid = R.get('pid', '')
    mid = R.get('mid', '')
    depart = R.get('department', None)
    executor = R.get('executor', None)
    name = R.get('name', '').capitalize()
    '''业务限制'''
    if name in set(['系统优化', '代码优化', '部署优化', 'Bug修改', 'Bug验证']) or len(name) < 6: 
        return ErrorResponseJson('提交失败，任务名应体现具体业务且任务能在短期内正常结束！')
    
    multi = {'true': 1, 'false': 0}[R.get('multi')]
    plan_time = R.get('date')
    description = R.get('description', '')
    if mid == "" or name == '' or plan_time == '': return ErrorResponseJson('模块名和描述不能为空！')
    
    data, msg = T.create_task(pid, mid, user, name, multi, plan_time, description, depart, executor)
    if not data: return ErrorResponseJson(msg if msg else '操作失败，请检查是否填写完整！')
    
    return NormalResponseJson({'id': data, 'error': msg}) 

@app.route('/listTask', methods=['GET', 'POST'])
@auth_required('lv0')    
def _list_task(user, R):
    project = R.get('project', None)
    pid = int(R.get('pid', -1))
    mid = int(R.get('mid', -1))
    category = R.get('category', '')
    department = R.get('department', '')
    hide_done = bool(R.get('hideDown', False))
    
    if mid != -1: 
        '''用于日报填报时的状态'''
        data = T.get_task_list(mid, "", category, department, hide_done)
    else:
        data = T.get_task_hint(user, pid, project)
    
    return NormalResponseJson(data)

@app.route('/getTaskControl', methods=['GET', 'POST'])
@auth_required('lv0')    
def _get_task_control(user, R):
    tid = R.get('tid', '')
    multi = R.get('multi')
    
    data = T.get_task_control(tid, user)
    
    return NormalResponseJson(data)

@app.route('/submitReport', methods=['GET', 'POST'])
@auth_required('lv0')    
def submit_report(user, R):
    params = R.get('params', '{}')
    data = json.loads(params, encoding="utf8")
    if not data: return ErrorResponseJson("参数错误")
    
    jobs = data.get('jobs', [])
    plans = data.get('plans', [])
    
    flag, data = RC.submit_record(user, jobs, plans)
    if not flag: return ErrorResponseJson("提交失败:" + data)
    
    return NormalResponseJson(data)

@app.route('/listReportDay', methods=['GET', 'POST'])
@auth_required('lv0')
def _list_report_day(user, R):
    user_ = R.get('user', '')
    if user_ == '': user_ = user
    department = R.get('department', None)
    data = RP.list_report_day(user_, department)
    
    return NormalResponseJson(data)

@app.route('/getReportDay', methods=['GET', 'POST'])
@auth_required('lv0')
def _get_report_day(user, R):
    user_ = R.get('user', '')
    if user_ == '': user_ = user
    department = R.get('department', None)
    workday = R.get('workday', None)
    data = RP.get_report_day(user_, department, workday)
    
    return NormalResponseJson(data)

@app.route('/loadRecords', methods=['GET', 'POST'])
@auth_required('lv0')
def load_records(user, R):
    data = RP.load_records(user)
    
    return NormalResponseJson(data)

@app.route('/loadLeftRecords', methods=['GET', 'POST'])
@auth_required('lv0')
def _load_left_records(user, R):
    params = R.get('params', '{}')
    dt = json.loads(params, encoding="utf8")
    jobs, plans = dt['jobs'], dt['plans']
    
    data = RP.load_left_records(user, jobs, plans)
    
    return NormalResponseJson(data)

@app.route('/saveReportSum', methods=['GET', 'POST'])
@auth_required('lv0')
def _save_report_sum(user, R):
    workday = R.get('workday', None)
    record = R.get('record', None)
    summary = R.get('summary', None)
    flag, data = RC.save_report_sum(user, workday, record, summary)
    if flag == -1: return ErrorResponseJson(data)
    
    return NormalResponseJson(data)


@app.route('/getSubmitStatus', methods=['GET', 'POST'])
@auth_required('lv0')
def _get_submit_status(user, R):
    data = RC.get_submit_status(user)
    
    return NormalResponseJson(data)

@app.route('/getTaskLeft', methods=['GET', 'POST'])
@auth_required('lv0')
def get_task_left(user, R):
    department = R.get('department', None)
    data = RP.list_task_left(user, department)
    
    return NormalResponseJson(data)

@app.route('/getReportWeek', methods=['GET', 'POST'])
@auth_required('lv0')
def _get_report_week(user, R):
    department = R.get('department', None)
    begin_time = R.get('beginTime', None)
    end_time = R.get('endTime', None)
    
    data = RP.get_report_week(begin_time, end_time, user, department)
    
    return NormalResponseJson(data)

@app.route('/getReportQuarter', methods=['GET', 'POST'])
@auth_required('lv0')
def _get_report_quarter(user, R):
    department = R.get('department', None)
    q = R.get('quarter', None)
    
    data = RP.get_report_quarter(q, user, department)
    
    return NormalResponseJson(data)

@app.route('/getReportCom', methods=['GET', 'POST'])
@auth_required('lv0')
def _get_report_com(user, R):
    department = R.get('department', None)
    begin_time = R.get('beginTime', None)
    end_time = R.get('endTime', None)
    
    data = RP.get_report_com(begin_time, end_time, user, department)
    
    return NormalResponseJson(data)

@app.route('/getReportProject', methods=['GET', 'POST'])
@auth_required('lv1')
def _get_report_project(user, R):
    department = R.get('department', None)
    day = R.get('day', None)
    
    data = RP.get_report_proj_day(day, department)
    
    return NormalResponseJson(data)

@app.route('/getReportProjectCom', methods=['GET', 'POST'])
@auth_required('lv0')
def _get_report_proj_com(user, R):
    department = R.get('department', None)
    begin_time = R.get('beginTime', None)
    end_time = R.get('endTime', None)
    cls = R.get('cls', None)
    if str(cls) == "1": department = None 
    
    data = RP.get_report_proj_com(begin_time, end_time, department)
    
    return NormalResponseJson(data)    

@app.route('/getReportMonth', methods=['GET', 'POST'])
@auth_required('lv0')
def _get_report_project_m(user, R):
    department = R.get('department', None)
    month = R.get('month', None)
    
    data = RP.get_report_month(month, user, department)
    
    return NormalResponseJson(data)

@app.route('/changeTaskName', methods=['GET', 'POST'])
@auth_required('lv0')
def change_task_name(user, R):
    t_id = R.get('tId', None)
    name = R.get('name', None)
    new_name = R.get('newName', None)
    CT.change_name(user, t_id, name, new_name)
    
    return NormalResponseJson("修改成功")
    
@app.route('/changePlan', methods=['GET', 'POST'])
@auth_required('lv0')
def change_plan(user, R):
    t_id = R.get('tId', None)
    src_time = R.get('lastTime', None)
    new_time = R.get('newTime', None)
    progress = R.get('progress', None)
    new_progress = R.get('newProgress', None)
    multi_user = R.get('multiUser', None)
    reason = R.get('reason', None)
    
    flag, msg = CT.change_plan(user, t_id, src_time, new_time, progress, new_progress,
        reason, multi_user)
    
    return NormalResponseJson("成功关闭任务")
     
@app.route('/closeTask', methods=['GET', 'POST'])
@auth_required('lv0')
def close_task(user, R):
    t_id = R.get('tId', None)
    reason = R.get('reason', None)
    progress = R.get('progress', None)
    flag, msg = CT.close_task(user, t_id, reason, progress)
    
    return NormalResponseJson("成功关闭任务")

@app.route('/finishTask', methods=['GET', 'POST'])
@auth_required('lv0')
def finish_task(user, R):
    t_id = R.get('tId', None)
    real_time = R.get('realTime', None)
    mark = R.get('mark', None)
    progress = R.get('progress', None)
    flag, msg = CT.finish_task(user, t_id, real_time, mark, progress)
    
    return NormalResponseJson("成功结束任务")

@app.route('/delTask', methods=['GET', 'POST'])
@auth_required('lv0')
def del_task(user, R):
    t_id = R.get('tId', None)
    flag, msg = CT.del_task(user, t_id)
    
    return NormalResponseJson("成功删除任务")

@app.route('/getReportOrg', methods=['GET', 'POST'])
@auth_required('lv0')
def get_report_org(user, R):
    department = R.get('department', None)
    begin_time = R.get('beginTime', None)
    end_time = R.get('endTime', None)
    
    data = RC.get_report_org(begin_time, end_time, department)
    
    return NormalResponseJson(data) 

@app.route('/getProjTimeSum', methods=['GET', 'POST'])
@auth_required('lv0')
def get_proj_time_sum(user, R):
    department = R.get('department', None)
    begin_time = R.get('beginTime', None)
    end_time = R.get('endTime', None)
    cls = R.get('cls', None)
    if str(cls) == "1": department = None 
    
    data = RC.get_proj_time_sum(begin_time, end_time, user, department)
    
    return NormalResponseJson(data) 

@app.route('/managePM', methods=['GET', 'POST'])
@auth_required('lv0')
def manage_pm(user, R):
    key = R.get('key', None)
    p_id = R.get('pId', None)
    m_id = R.get('mId', None)
    t_id = R.get('tId', None)
    name = R.get('name', None)
    pre = R.get('pre', None)
    data, err = P.manage_pm(key, p_id, m_id, t_id, name, pre, user)
    if not data: return ErrorResponseJson("操作失败:" + str(err))
    
    return NormalResponseJson(data)

@app.route('/listUser', methods=['GET', 'POST'])
@auth_required('lv0')
def list_user(user, R):
    org_id = R.get('orgId', None)
    data = T.get_user_list(org_id)
    
    return NormalResponseJson(data)

@app.route('/searchTask', methods=['GET', 'POST'])
@auth_required('lv0')
def search_task(user, R):
    key = R.get('key', None)
    p_id = R.get('pId', None)
    
    data = T.search_task(key, p_id)
    
    return NormalResponseJson(data)


if __name__ == '__main__':
    L.info('server start on: %s !' % (C.PORT))
    app.debug=False
    app.run(host='0.0.0.0', port=C.PORT)

